package com.kh.first.controller;

import com.kh.first.pojo.common.AjaxJson;
import lombok.Cleanup;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("upload")
public class UploadController {
    @Value("${upload.image.path}")
    String imagePath;

    @RequestMapping(params = "upStringImg")
    @ResponseBody
    public AjaxJson<String> upStringImg(String png) throws IOException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        if (null == png || "".equals(png)) {
            ajaxJson.data = "程序有问题，请联系管理员";
            ajaxJson.code = -1;
            return ajaxJson;
        }
        byte[] b64Png = Base64.decodeBase64(png.replace("data:image/png;base64,", ""));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String savedFileName = uuid + ".png";
        String pathname = imagePath + File.separator + savedFileName;

        @Cleanup
        FileOutputStream fos = new FileOutputStream(pathname);
        fos.write(b64Png);
        fos.flush();
        ajaxJson.data = savedFileName;

        return ajaxJson;
    }
}
